<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="this.type == 1">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['crm:busProduct:add']"
        >编辑产品</el-button>
      </el-col>
      <el-col :span="1.5" v-if="this.type == 1">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['crm:busProduct:remove']"
        >删除</el-button>
      </el-col>
      <div style="float:right;">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="getList"
        >刷新</el-button>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="busProductList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品名称" align="center" prop="proName" />
      <el-table-column label="产品规格" align="center" prop="proSpecs" />
      <el-table-column label="产品型号" align="center" prop="proModel" />
      <el-table-column label="颜色" align="center" prop="proColor" />
      <el-table-column label="产品单位" align="center" prop="proUnit" />
      <el-table-column label="产品单价(元)" align="center" prop="price" />
      <el-table-column label="销售价格(元)" align="center" prop="salesPrice" />
      <el-table-column label="数量" align="center" prop="num" />
      <el-table-column label="小计(元)" align="center" prop="subtotal">
        <template slot-scope="scope">
          {{scope.row.num * scope.row.salesPrice}}
        </template>
      </el-table-column>
      <!--<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['crm:busProduct:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['crm:busProduct:remove']"
          >删除</el-button>
        </template>
      </el-table-column>-->
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商机产品关系对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddCrmBusinessStatus">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteCrmBusinessStatus">删除</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="busProductList" :row-class-name="rowBusProIndex" @selection-change="handleSelectionChange1" ref="refBusProductList" :key = "tablekey">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="产品名称" align="center" prop="proName" />
          <el-table-column label="产品型号" align="center" prop="proModel" />
          <el-table-column label="颜色" align="center" prop="proColor" />
          <el-table-column label="产品单位" align="center" prop="proUnit" />
          <el-table-column label="产品单价(元)" align="center" prop="price" />
          <el-table-column label="销售价格(元)" align="center" prop="salesPrice">
            <template slot-scope="scope">
              <el-input-number @change="()=>tablekey=!tablekey" v-model="scope.row.salesPrice" controls-position="right" :min="0" style="width:120px;" @input="salesPriceChange(scope.row)"/>
            </template>
          </el-table-column>
          <el-table-column label="最低价格(元)" align="center" prop="minPrice" />
          <el-table-column label="数量" align="center" prop="num">
            <template slot-scope="scope">
              <el-input-number @change="()=>tablekey=!tablekey" v-model="scope.row.num" controls-position="right" :min="1" style="width:120px;"/>
            </template>
          </el-table-column>
          <el-table-column label="小计(元)" align="center">
            <template slot-scope="scope">
              {{scope.row.num * scope.row.salesPrice}}
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormBusPro">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择产品 -->
    <el-dialog :title="selProtitle" :visible.sync="selProOpen" width="70%" append-to-body>
      <selBusPro @selAddBusProduct = "selAddBusProduct" @selBusProductClose = "selBusProductClose" :isNewTime = "this.isNewTime"></selBusPro>
    </el-dialog>
  </div>
</template>

<script>
import { listBusProduct, getBusProduct, delBusProduct, addBusProduct, updateBusProduct, exportBusProduct } from "@/api/crm/busProduct/busProduct";
import { getCrmBusProductById } from "@/api/crm/business/business";
import selBusPro from '../product/selBusPro';

export default {
  props: {
      businessId: "",
      type: ""
  },
  name: "BusProduct",
  components: {
    selBusPro
  },
  data() {
    return {
      selProtitle: "",
      selProOpen: false,
      tablekey: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商机产品关系表格数据
      busProductList: [],
      //新打开窗口刷新产品列表
      isNewTime: new Date(),
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        businessId: null,
      },
      //选中的产品
      selBusProduct: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
  //  this.getList();
  },
  methods: {
    /** 判断价格，销售价格不能低于最低价格 */
    salesPriceChange(row){
      if(row.salesPrice < row.minPrice){
        this.$alert("销售价格不能低于产品最低价格", "提示", { confirmButtonText: "确定", });
        row.salesPrice = row.minPrice
      }
    },
    /** 商机-产品添加按钮操作 */
    handleAddCrmBusinessStatus() {
      this.isNewTime = new Date() + Math.round(Math.random()*50000);
      this.selProtitle = "选择产品";
      this.selProOpen = true;
    },
    /** 选择产品后插入 */
    selAddBusProduct(selections){
      selections.map((item, index) => {
        item.productId = item.id;
        item.salesPrice = item.price;
        item.num = 1;
        item.type = this.type;
        item.businessId = this.businessId;
        this.busProductList.push(item);
      })
      this.selProOpen = false;
    },
    /** 关闭产品选择框 */
    selBusProductClose(selection){
      this.selProOpen = false;
    },
    /** 商机-产品删除按钮操作 */
    handleDeleteCrmBusinessStatus() {
      if (this.selBusProduct.length == 0) {
        this.$alert("请先选择要删除的产品数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.busProductList.splice(this.selBusProduct[0].index - 1, 1);
      }
    },
	  /** 商机状态序号 */
    rowBusProIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    // 多选框选中数据
    handleSelectionChange1(selection) {
      if (selection.length > 1) {
        this.$refs.refBusProductList.clearSelection();
        this.$refs.refBusProductList.toggleRowSelection(selection.pop());
      } else {
        this.selBusProduct = selection;
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查询商机产品关系列表 */
    getList() {
      this.busProductList = [];
      this.loading = true;
      let params = {businessId: this.businessId, type: this.type}
      listBusProduct(params).then(response => {
        this.busProductList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.getList();
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        businessId: null,
        productId: null,
        price: null,
        salesPrice: null,
        num: null,
        discount: null,
        subtotal: null,
        unit: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBusProduct(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改产品";
      });
    },
    /** 提交按钮商机-产品 */
    submitFormBusPro() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.busProductList.length == 0){
            this.$alert("请先选择产品", "提示", { confirmButtonText: "确定", });
          }else{
            updateBusProduct(this.busProductList).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.$emit('getBusinessInfo');
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除产品编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBusProduct(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商机产品关系数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportBusProduct(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  },
  watch: {
      businessId: {
      　　handler(newValue, oldValue) {
      　　    if(null != newValue && "undefined" != newValue){
                this.getList();
              }
      　　},
          deep: true,
      　　immediate: true
      }
  } 
};
</script>
